If the digits cannot be converted into a 32-bit int
an Exception
is thrown.
This limits the input to the range of an int
, roughly plus or minus 2 billion.
hasNextInt()
import java.util.Scanner;
import java.io.*;
class ManySquares
{
public static void main (String[] args) throws IOException
{
File file = new File("myData.txt"); // create a File object
Scanner scan = new Scanner( file ); // connect a Scanner to the file
int num, square;
while( scan.hasNextInt() ) // is there more data to process?
{
num = scan.nextInt();
square = num * num ;
System.out.println("The square of " + num + " is " + square);
}
}
}
Most files contain a great deal of data.
Practical programs must process this data using a loop of some sort.
Here is a program that reads a text
file that contains many integers and writes the square of each one.
The loop reads integers from the file one by one
until the end of file is reached or until input unsuitable for nextInt()
is encountered.
However, a correct square will be computed only for those input values less than the square root of 2 billion, roughly 46000. Integers larger than this result in overflow.
The hasNextInt()
method returns true
if the next set of characters in the input
stream can be read in as an int
.
If they can't be read as an int
,
or they are too big for an int
or if the end of the file has been reached, then it returns false.
hasNextInt()
itself does not consume any characters.
Say that the following is in the file myData.txt
.
What is the expected output of the program?
1 6 3 oops 9 12